package com.xunbao.thread.util;

import net.sf.json.JSONObject;

import java.util.concurrent.*;

/**
 * Created with IntelliJ IDEA.
 * ClassName:CompletionServiceTest
 * Description:
 * Author:yijiawei
 * Date: 2016/5/31 9:52
 */
public class CompletionServiceTest {

    public static void main(String[] args) {

        ExecutorService executorService = Executors.newCachedThreadPool();
        CompletionService completionService = new ExecutorCompletionService(executorService);

        executorService.submit(new RunnableTask(completionService));

        for (int i = 0; i < 3; i++) {
            if (i == 2) {
                completionService.submit(new MyTaskWithResult("two"));
            } else {
                completionService.submit(new MyTaskWithResult("one" + i));
            }
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }


    }
}

class RunnableTask implements Runnable {

    private CompletionService completionService;

    public RunnableTask(CompletionService completionService) {
        this.completionService = completionService;
    }

    @Override
    public void run() {
        while (true) {
            try {
                Future<ResultObject> result = completionService.take();
                if (result == null) {
                    System.out.println("---------------- NULL -----------------------");
                    TimeUnit.SECONDS.sleep(1);
                    continue;
                }
                try {
                    System.out.println("result = " + JSONObject.fromObject(result.get()));
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
